package com.qclix.inv.textui;

import com.qclix.inv.Invoice;
import com.qclix.inv.InvoiceService;
import com.qclix.inv.InvoiceServiceException;

import java.io.*;
import java.util.List;

/**
 * Handles the generation of a pdf file for one of the last invoice(s)
 */
public class PdfLastInvoiceHandler extends AbstractActionHandler {

    private InvoiceService invoiceService;

    public void setInvoiceService(InvoiceService invoiceService) {
        this.invoiceService = invoiceService;
    }

    public void handle() {
        setNextHandler(FlowHandler.HANDLER.topMenu);
        List<Invoice> invoices;
        try {
            invoices = invoiceService.getLastInvoices();
        } catch (InvoiceServiceException e) {
            System.out.println("An error occurred while retrieving the last invoices");
            return;
        }

        if (invoices.size() == 0) {
            System.out.println("There is no last invoice!");
            return;
        }

        Invoice chosenInvoice;
        System.out.println("Choose an invoice:");
        int size = 9 > invoices.size() ? invoices.size():9; 

        for (int i = 1; i <= size; i++) {
            System.out.println("(" + i + ") " + invoices.get(i-1).getNumber());
        }
        chosenInvoice = invoices.get(Integer.parseInt(readChoice("1")) - 1);

        File directory;
        do {
            System.out.print("Enter path: (/home/pierre) ");
            directory = new File(readValue(System.getProperty("user.home")));
            if (!directory.exists()) {
                directory = null;
                System.out.println("Directory doesn't exist !");
            } else if (! directory.canWrite()) {
                directory = null;
                System.out.println("Directory is not writable !");
            }
        } while (directory == null);

        File outputFile = new File(directory, chosenInvoice.getNumber() + ".pdf");
        System.out.println("The file is " + outputFile.getAbsolutePath());
        try {
            invoiceService.writePDF(chosenInvoice, outputFile);
        } catch (InvoiceServiceException e) {
            throw new RuntimeException(e);
        }

        setNextHandler(FlowHandler.HANDLER.topMenu);
    }
}
